#include <iostream>
#include <string>
#include <functional>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#include <pthread.h>
#include <sys/types.h>
#include <sys/wait.h>

#include "InetAddr.hpp"
#include "Log.hpp"
// #include "ThreadPool.hpp"


void usage(std::string proc){
    std::cout << "usage is \n\t" << proc << "  client_ip  client_port" << std::endl;
}

int main(int argc, char* argv[]){
    if(argc != 3){
        usage(argv[0]);
        exit(1);
    } 
    //1.0 设置好服务器ip地址和端口号  
    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);

    //2.0创建套接字
    ssize_t sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0){
        std::cerr << "sockfd is faild \n";
        exit(2);
    }
    
    //3，0设置服务端的消息
    sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(ip.c_str());

    int n = connect(sockfd, (struct sockaddr*)&server, sizeof(server));
    if(n < 0){
        LOG(FATAL, "connect fail\n");
        exit(3);
    }

    while(true){
        std::cout << "Please enter message: ";
        std::string message;
        std::getline(std::cin, message);
        int n = send(sockfd, message.c_str(), message.size(), 0);
        if(n < 0) {
            LOG(ERROR,"wiret fail\n");
        } else if (n > 0) {
            char buffer[1024];
            int m = recv(sockfd, buffer, sizeof(buffer) - 1, 0);
            if(m > 0){
                buffer[m] = 0; 
                std::cout << "server echo# " << buffer << std::endl;
            }
            
        }
    }

    ::close(sockfd);
    return 0;
}